﻿using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Publicuse.Util.Redis
{
    /// <summary>
    ///  Redis管理中心
    /// </summary>
    public sealed class ServiceStackManager
    {
        /// <summary>
        /// Redis客户端池化管理
        /// </summary>
        private static Dictionary<string, PooledRedisClientManager> prcManager;

        private static ServiceStackManager redisManager = null;

        static ServiceStackManager()
        {
            redisManager = new ServiceStackManager();
            prcManager = new Dictionary<string, PooledRedisClientManager>();
        }

        public static ServiceStackManager GetRedisManager
        {
            get { return redisManager; }
        }

        public static readonly object lockcon = new object();

        /// <summary>
        /// 创建链接池管理对象
        /// </summary>
        private IRedisClient CreateManager(int conIndex, int dbIndex = 0)
        {
            lock (lockcon)
            {
                if (!prcManager.ContainsKey(conIndex + "-" + dbIndex))
                {
                    var key = conIndex + "-" + dbIndex;
                    var con = ServiceStackProvider.GetInstance(conIndex).GetConnection(dbIndex);
                    prcManager.Add(key, con);
                }
                return prcManager.FirstOrDefault(o => o.Key == conIndex + "-" + dbIndex).Value.GetClient();
            }
        }

        /// <summary>
        /// 获取连接索引库
        /// </summary>
        /// <param name="conIndex"></param>
        /// <param name="dbIndex"></param>
        /// <returns></returns>
        public IRedisClient GetClient(int conIndex, int dbIndex = 0)
        {
            try
            {
                if (prcManager.Count == 0)
                {
                    return this.CreateManager(conIndex, dbIndex);
                }
                else
                {
                    var con = prcManager.Any(o => o.Key == conIndex + "-" + dbIndex);
                    if (con)
                    {
                        return prcManager.FirstOrDefault(o => o.Key == conIndex + "-" + dbIndex).Value.GetClient();
                    }
                    else
                    {
                        return this.CreateManager(conIndex, dbIndex);
                    }
                }
            }
            catch (Exception ex)
            {
                //LogUtil.GetInstance.WriteLogOld("获取Redis链接", conIndex + "|" + dbIndex + "|" + ex.Message + " |" + ex.StackTrace, false);
                return null;
            }

        }
    }
}
